const {addUser,findUser,findUserList,deleteUser,updateUser,loginUser}= require("../models/users.js");
const {hash,compare,token,verify}=require("../utils/encryption.js");
const randomstring=require("randomstring");

//添加用户
const signup=async(req,res,next)=>{
    res.set("content-type","application/json;charset=utf-8");
    // console.log(req.body);
    let {username,dearname,age,password}=req.body;
    // let hashPassword=await hash(Buffer.from(password.toString()));
    let hashPassword=await hash(password.toString());//密码加密
    // console.log(hashPassword);
    let findRes=await findUser(username);//添加的用户查询是否已存在重名
    if(findRes.length!=0){
        res.render("fail.ejs",{
            data:JSON.stringify({
                message:"用户名重复!"
            })
        });
    }else{
        let addRes=await addUser({username,dearname,age,password:hashPassword});//将用户加入数据库中
        // console.log(addRes);
        res.render("success.ejs",{
            data:JSON.stringify({
                message:"添加用户成功!"
            })
        });
    };
};
//用户列表数据查询
const list=async(req,res,next)=>{
    res.set("content-type","application/json;charset=utf-8");
    let result=await findUserList();
    res.render("success.ejs",{
        data:JSON.stringify(result)
    });
};
//删除用户数据
const deleteData=async(req,res,next)=>{
    res.set("content-type","application/json;charset=utf-8");
    let id=req.body.id;
    let result=await deleteUser(id);
    // console.log(result);
    if(result.deletedCount==1){
        res.render("success.ejs",{
            data:JSON.stringify({
                message:"用户删除成功"
            })
        });
    }else{
        res.render("fail.ejs",{
            data:JSON.stringify({
                message:"用户删除失败"
            })
        });
    };
};
//修改用户数据
const updateData=async(req,res,next)=>{
    res.set("content-type","application/json;charset=utf-8");
    let {id,username,dearname,age}=req.body;
    // console.log(id,username,dearname,age,password);
    let result=await updateUser({id,username,dearname,age});
    // console.log(result);
    if(result.ok){
        res.render("success.ejs",{
            data:JSON.stringify({
                message:"用户修改成功"
            })
        });
    }else{
        res.render("fail.ejs",{
            data:JSON.stringify({
                message:"用户修改失败"
            })
        });
    };
};
//用户登录
const loginData=async(req,res,next)=>{
    res.set("Content-Type","application/json;charset=utf-8");
    let {username,password}=req.body;
    //先验证用户名是否存在
    let resultName=await findUser(username);
    if(resultName.length!==0){//说明用户存在
        let {password:passwordHash}=resultName[0];
        let resultCompare=await compare(password,passwordHash);
        if(resultCompare){
            // let sessionId=randomstring.generate();
            // res.set("set-cookie",`sessionId=${sessionId};Path=/;HttpOnly`);
            // res.cookie("sessionId",sessionId,{//设置cookie，需要借助于中间件cookie-parser
            //     path:"/",
            //     httpOnly:false,
            //     maxAge:1000*60*24
            // });
            // req.session.username=username;//设置session
            let tk=token(username);
            // console.log(tk);
            res.set("X-Access-Token",tk);
            res.render("success.ejs",{
                data:JSON.stringify({
                    username
                })
            });
        }else{
            res.render("fail.ejs",{
                data:JSON.stringify({
                    message:"用户名或密码错误"
                })
            });
        };
    }else{//用户不存在
        res.render("fail.ejs",{
            data:JSON.stringify({
                message:"用户名不存在"
            })
        });
    };
};
//用户退出登录
const exitData=async(req,res,next)=>{
    res.set("Content-Type","application/json;charset=utf-8");
    // req.session=null;//清空session
    res.render("success.ejs",{
        data:JSON.stringify({
            message:"退出登录"
        })
    });
};
//进入项目判断用户是否已登录
const isAuth=async(req,res,next)=>{
    res.set("Content-Type","application/json;charset=utf-8");
    //token方式
    let tk=req.get("X-Access-Token");
    try {
        let result=verify(tk);
        res.render("success.ejs",{
            data:JSON.stringify({
                username:result.username
            })
        });
    } catch (error) {
        res.render("fail.ejs",{
            data:JSON.stringify({
                message:"请登录"
            })
        });
    };
    //session-cookie方式
    // if(req.session.username){
    //     res.render("success.ejs",{
    //         data:JSON.stringify({
    //             username:req.session.username
    //         })
    //     });
    // }else{
    //     res.render("fail.ejs",{
    //         data:JSON.stringify({
    //             message:"请登录"
    //         })
    //     });
    // };
};

module.exports={
    signup,
    list,
    deleteData,
    updateData,
    loginData,
    exitData,
    isAuth
};